#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
简单的数据验证脚本
直接查询数据库中的商品和订单数据
"""

import os
import sys
# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import asyncio
import logging
from datetime import datetime

# 配置日志

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)

async def verify_data():
    """
    验证数据库中的商品和订单数据
    """
    try:
        # 导入必要的模块
        from database.connection import get_session
        from database.models import Product, Order, ShopifySyncLog
        from sqlmodel import select
        
        # 1. 查询商品数据
        logger.info("=== 检查商品数据 ===")
        async for session in get_session():
            try:
                # 查询所有商品
                stmt = select(Product)
                result = await session.execute(stmt)
                products = result.scalars().all()
                logger.info(f"发现 {len(products)} 个商品")
                
                for product in products:
                    logger.info(f"商品ID: {product.id}, 名称: {product.name}, 价格: {product.price}")
                    logger.info(f"  - Shopify商品ID: {product.shopify_product_id}")
                    logger.info(f"  - 分类ID: {product.category_id}, 库存: {product.stock_quantity}")
                
                # 2. 查询订单数据
                logger.info("\n=== 检查订单数据 ===")
                stmt = select(Order)
                result = await session.execute(stmt)
                orders = result.scalars().all()
                logger.info(f"发现 {len(orders)} 个订单")
                
                for order in orders:
                    logger.info(f"订单ID: {order.id}, 订单号: {order.order_number}, 总金额: {order.total_amount}")
                    logger.info(f"  - 用户ID: {order.user_id}, 商品ID: {order.product_id}")
                    logger.info(f"  - 3D模型ID: {order.model_3d_id}, 数量: {order.quantity}")
                    logger.info(f"  - 状态: {order.status}, 支付状态: {order.payment_status}")
                    logger.info(f"  - 收货人: {order.shipping_name}, 手机号: {order.shipping_phone}")
                    logger.info(f"  - Shopify订单ID: {order.shopify_order_id}")
                
                # 3. 查询同步日志 (避免枚举类型错误)
                logger.info("\n=== 检查同步日志 ===")
                # 使用原始SQL来避免枚举类型限制
                result = await session.execute(
                    "SELECT id, shopify_resource_id, shopify_operation, sync_status, created_at, error_message "
                    "FROM shopify_sync_logs ORDER BY created_at DESC LIMIT 5"
                )
                logs = result.fetchall()
                logger.info(f"最近5条同步日志:")
                
                for log in logs:
                    logger.info(f"日志ID: {log[0]}, 资源ID: {log[1]}, 操作: {log[2]}")
                    logger.info(f"  - 状态: {log[3]}, 时间: {log[4]}")
                    if log[5]:
                        logger.info(f"  - 错误: {log[5]}")
                
                logger.info("\n✅ 数据验证完成！")
                logger.info(f"总计: {len(products)} 个商品, {len(orders)} 个订单")
                break
                
            except Exception as e:
                logger.error(f"查询过程中出错: {str(e)}")
                break
        
    except Exception as e:
        logger.error(f"验证过程中出现错误: {str(e)}")

if __name__ == "__main__":
    logger.info("开始数据验证...")
    asyncio.run(verify_data())
    logger.info("数据验证结束！")